#include<iomanip>
#include<iostream>
#include<utility>
#include<string>
#include<unordered_map>
#include<set>
#include<vector>
#include<fstream>
#include<sstream>

using std::endl;
using std::cin;
using std::cout;
using std::unordered_map;
using std::string;
using std::set;
using std::vector;
using std::multiset;
using std::ifstream;
using std::istringstream;

class Dict
{
public:

    //readfile

    void read_file(const string& lhs)
    {
        //打开文件

        ifstream ifs(lhs);
        if(!ifs)
        {
            cout<<lhs<<" opne failed"<<endl;
            return;
        }
        //文件输入流创建读每行

        string line;
        int linenum=0;
        _line.push_back("begin");
        while(getline(ifs,line))
        {
            //拿到每行的数据先放入vector
            _line.push_back(line);
            ++linenum;

            //处理行

            for(auto& i:line)
            {
                if(!isalpha(i))
                {
                    i=' ';
                }
                else 
                {
                    i=tolower(i);
                }
            }
            //对行数据处理完成开启字符串流
            istringstream iss(line);

            if(!iss)
            {
                cout<<" 字符串流打开失败 "<<endl;
            }

            string word;

            while(iss>>word)
            {
                _dict[word].insert(linenum);
            }
            //单词输入完成
        }
        ifs.close();
    }

    void check_word(string word)
    {
        cout<<"**********************************"<<endl;
        for(auto& i: word)
        {
            i=tolower(i);
        }
        if(!_dict.count(word))
        {
            cout<<"word: "<<word<<" don't exit"<<endl;
        }
        else
        {
            size_t times=_dict[word].size();
            if(times==1)
            {
                cout<<"word: "<<word<<" occurs "<<times<< " time"<<endl;
            }
            else 
            {
                cout<<"word: "<<word<<" occurs "<<times<< " times"<<endl;
                set<int> putline(_dict[word].begin(),_dict[word].end());

                for(auto & i:putline)
                {
                    cout<<"(line "<<i<<") "<<std::setw(10)<< _line[i]<<endl;
                }
            }


        }
    }



    //put_to
private:
    vector<string> _line;
    unordered_map<string,multiset<int>> _dict;
};

int main(void)
{
    Dict pt;
    string filename;
    cout<<"请输入文件名"<<endl;
    cin>>filename;
    pt.read_file(filename);

    cout<<"请输入要查找的单词"<<endl;
    string word;
    cin>>word;
    pt.check_word(word);

}
